import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'

import {
  Message
} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken
} from '../utils/auth' // get token from cookie

NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

Vue.use(Router)
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

import Layout from '@/layout/layout'

// 静态路由
export const constantRoutes = [{
    path: '/redirect',
    component: Layout,
    hidden: true,
    children: [{
      path: '/redirect/:path*',
      component: () => import('@/views/Redirect/Redirect')
    }]
  },
  {
    path: '/login',
    component: () => import('@/views/Login/Login'),
    hidden: true,
    meta: {
      title: '登录',
    }
  },
  {
    path: '/404',
    component: () => import('@/views/Page404/Page404'),
    hidden: true,
    meta: {
      title: '404',
    }
  },

  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [{
      path: 'dashboard',
      name: 'Dashboard',
      component: () => import('@/views/Dashboard/Dashboard'),
      meta: {
        title: '主页',
        icon: 'example',
        affix: true
      }
    },
    {
      path: '/test',
      component: () => import('@/views/test'),
      hidden: true,
      meta: {
        title: '抽查计划分配页面',
      }
    }],
  },

  {
    path: '*',
    redirect: '/404',
    hidden: true
  }
]

const createRouter = () => new Router({
  mode: 'hash',
  scrollBehavior: () => ({
    y: 0
  }),
  routes: constantRoutes
})

const router = createRouter()

// 重置路由
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher
}

const whiteList = ['/login', '/404']
router.beforeResolve()
router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = to.meta.title

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    next()
    if (to.path === '/login') {
      next({
        path: '/'
      })
      NProgress.done()
    } else {
      try {
        const routes = await store.dispatch('permission/generateRoutes')
        console.log(routes)
        router.addRoutes(routes)
        NProgress.done()
        if (to.redirectedFrom) { // 修复动态页面刷新404问题
          next({
            path: to.redirectedFrom
          })
        } else {
          next()
        }
      } catch (error) {
        await store.dispatch('user/clear')
        Message.error(error || 'Has Error')
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }

  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router
